package com.xiaozhen.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaozhen.blog.entity.User;
import com.xiaozhen.blog.mapper.MenuMapper;
import com.xiaozhen.blog.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @create 2023-05-11 20:13
 * 实现 UserDetailsService
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从 MySQL 数据库查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,username);
        User user = userMapper.selectOne(wrapper);
        // 如果 user 为 null
        if (Objects.isNull(user)){
            throw new RuntimeException("用户名或者密码错误");
        }
        // 查询对应的权限信息
        List<String> list = menuMapper.selectPermsByUserId(user.getId());

        // 把数据封装成 UserDetails 类，并返回
        return new LoginUser(user,list);
    }
}
